/*
 * Copyright (C) 2011 Sony Ericsson Mobile Communications AB.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */
package com.sonyericsson.example3;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import android.app.Activity;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

public class AlbumArtworkExtensionActivity extends Activity {

	private long mAudioId;
	private long mAlbumId;
	private static final Uri sArtworkUri = Uri.parse("content://media/external/audio/albumart");
	
	@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        
        setContentView(R.layout.main);
        setTitle(R.string.description);

        // Retrieve the URI from the intent, this is a URI to a MediaStore audio
        // file
        Intent intent = getIntent();
        Uri trackUri = intent.getData();
		
        // Define the columns we want to retrieve for the audio file
        // Note ALBUM_ART column is not present
		final String[] cols = new String[] { 
					MediaStore.Audio.Media._ID,
					MediaStore.Audio.Media.TITLE,
					MediaStore.Audio.Media.ARTIST,
					MediaStore.Audio.Media.ALBUM,
					MediaStore.Audio.Media.DATE_ADDED,
					MediaStore.Audio.Media.DATE_MODIFIED,
					MediaStore.Audio.Media.SIZE,
					MediaStore.Audio.Media.DATA,
                    MediaStore.Audio.Media.DISPLAY_NAME,
                    MediaStore.Audio.Media.DURATION,
                    MediaStore.Audio.Media.ALBUM_ID
			      	};
        

        // Use it to query the media provider
        Cursor trackCursor = getContentResolver().query(
                trackUri,
                cols, null, null, null);

        if (trackCursor != null) {
            try {
                if (trackCursor.moveToFirst()) {

                	
                	// And retrieve the wanted information
        			String idStr = trackCursor.getString(trackCursor
        					.getColumnIndexOrThrow(MediaStore.Audio.Media._ID));        			
                    String trackName = trackCursor.getString(trackCursor
                            .getColumnIndexOrThrow(MediaStore.Audio.Media.TITLE));
                    String artistName = trackCursor.getString(trackCursor
                            .getColumnIndexOrThrow(MediaStore.Audio.Media.ARTIST));
                    String albumName = trackCursor.getString(trackCursor
                            .getColumnIndexOrThrow(MediaStore.Audio.Media.ALBUM));

                    ((TextView)findViewById(R.id.audioId)).setText("ID: " + idStr);
                    ((TextView)findViewById(R.id.track)).setText("Track Name: " + trackName);
                    ((TextView)findViewById(R.id.album)).setText("Album Name: " + albumName);
                    ((TextView)findViewById(R.id.artist)).setText("Artist Name: " + artistName);
                    //((TextView)findViewById(R.id.dateAdded)).setText("Date Added: " + dateAdded);
                    //((TextView)findViewById(R.id.dateModified)).setText("Date Modified: " + dateModified);
                    //((TextView)findViewById(R.id.location)).setText("File Location: " + location);
                    //((TextView)findViewById(R.id.displayName)).setText("Display Name: " + displayName);
                    
                    //TODO: Consider listing music database information?
                    ///data/data/com.android.providers.media/databases/external-....db
                    
                    //Store until the view has been layed out, as view.width and height
                    //return 0 in onCreate
                    mAlbumId = trackCursor.getLong(trackCursor.getColumnIndexOrThrow(MediaStore.Audio.Media.ALBUM_ID));
                    
                    mAudioId = trackCursor.getLong(trackCursor.getColumnIndexOrThrow(MediaStore.Audio.Media._ID));
                }
            }
            finally {
                trackCursor.close();
            }
        }
        
        Button setButton = (Button) findViewById(R.id.button1);
        setButton.setOnClickListener(btn_listener);

    }
	
    private OnClickListener btn_listener = new OnClickListener() {
    	public void onClick(View v) {
    		Button b = (Button) v;
    		if(b.getId() == R.id.button1) {
    			String fileName = "dimg"+ mAlbumId + ".jpg";
    			boolean inError = false;
    			// Set the artwork for the current album to a test image...
    			try {    			
	    			InputStream ins = getResources().openRawResource(R.drawable.default_album);  
	    			int size = ins.available();  // Read the entire resource into a local byte buffer. 
	    			byte[] buffer = new byte[size]; 
	    			ins.read(buffer); 
	    			ins.close(); 
	    			
	    			
	    			
					File tempFile = new File(Environment.getExternalStorageDirectory() + "/websave", fileName);     
					if(!tempFile.exists()){    
						tempFile.createNewFile(); 
					}
	    			FileOutputStream fos = new FileOutputStream(tempFile);   
					fos.write(buffer); 
	    			fos.close(); 
    			}
    			catch(FileNotFoundException fntex) {
    				Toast.makeText(v.getContext(), "FileNotFound", Toast.LENGTH_SHORT).show();
    				fntex.printStackTrace();
    				inError = true;
    			}
    			catch(IOException ioex) {
    				Toast.makeText(v.getContext(), "IOException" + ioex.getMessage(), Toast.LENGTH_SHORT).show();
    				ioex.printStackTrace();
    				inError = true;
    			}
    			catch(Exception ex) {
    				Toast.makeText(v.getContext(), "Exception", Toast.LENGTH_SHORT).show();
    				inError = true;
    			}
    			
    			if(!inError) {    			
					boolean result = setAlbumArtworkFile("/sdcard/websave/" + fileName, mAudioId, mAlbumId);
					if(result) {
						Toast.makeText(v.getContext(), "Image set as album artwork", Toast.LENGTH_SHORT).show();
					} else {
						Toast.makeText(v.getContext(), "Failed to set as album artwork", Toast.LENGTH_SHORT).show();
					}
    			}
    			
    			//TODO get from gracenote/wiki etc

    		} 
    	}
    };
    
	public boolean setAlbumArtworkFile(String fileName, long songid, long albumId) {
		boolean success = false;
		ContentResolver res = getContentResolver();   
		ContentValues values = new ContentValues();
        values.put("album_id", albumId);
        values.put("_data", fileName);
        Uri newuri = res.insert(sArtworkUri, values);
        //success insert gives uri of content://media/external/audio/albumart/1
        if (newuri == null) {
               // Failed to insert in to the database. The most likely
               // cause of this is that the item already existed in the
               // database, so issue an update for that item with the new uri
        	   int ures = res.update(ContentUris.withAppendedId(sArtworkUri, albumId), values, null, null);
        	   if(ures == 1) {
        		   success = true;
        	   } else {        	
        		   success = false;
        	   }
         } else {
        	//success insert gives uri of content://media/external/audio/albumart/1
        	 success = true;
         }
        return success;
		
	}
		
	/***
	 * Gets the Id for the given track URI
	 * @param trackUri
	 * @return
	 */
	private int getIdForTrack(Uri trackUri) {
		
        Cursor trackCursor = getContentResolver().query(
                trackUri,
                new String[] { MediaStore.Audio.Media._ID }, null, null, null);
        int id = -1;
        if (trackCursor != null) {
        	trackCursor.moveToFirst();
            if (!trackCursor.isAfterLast()) {
                id = trackCursor.getInt(0);
            }
        }
        trackCursor.close();
        return id;
	}
       
}
